<?php

namespace App\Kuafu\Common\Service;

use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\CommonException;
use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\Order\Model\SeparateTimeLogModel;

class SeparateService
{
    private int $startTime, $endTime;
    private int             $separateTime;

    public function __construct(int $startTime, int $endTime)
    {
        $this->setSeparateTime();
        $this->setStartEndTime($startTime, $endTime);
    }

    private function setStartEndTime(int $startTime, int $endTime)
    {
        $this->startTime = $startTime;
        $this->endTime   = $endTime;
    }

    private function setSeparateTime()
    {
        $this->separateTime = self::getSeparateTime();
    }

    public static function getSeparateTime(): int
    {
        $date = (string)optional(ConfigModel::getConfigByTypeKeyOne('common', 'bakSeparateTime.' . config('app.env'), 60))
            ->value;

        return (int)strtotime($date);
    }

    /**
     * 更新隔断日期
     * @param int $t
     * @param bool $verifyDate 校验日期，只能往后更新
     * @return int
     */
    public static function updateSeparateTime(int $t, bool $verifyDate = true): int
    {
        if ($verifyDate) {

            $currentT = self::getSeparateTime();
            if ($currentT >= $t) {
                return 0;
            }
        }

        return ConfigModel::query()
                          ->where('type', 'common')
                          ->where('key', 'bakSeparateTime.' . config('app.env'))
                          ->update([
                              'value' => date('Y-m-d', $t),
                          ]);
    }

    const DB         = 'db';
    const CLICKHOUSE = 'clickhouse';

    /**
     * 检查并获取数据库类型
     * @return string
     * @throws CommonException
     */
    public function check(): string
    {
        if ($this->startTime >= $this->separateTime) {

            SeparateTimeLogModel::add($this->startTime, $this->endTime, SeparateTimeLogModel::TYPE_MYSQL);

            // db
            return self::DB;
        }

        if ($this->endTime <= $this->separateTime) {

            SeparateTimeLogModel::add($this->startTime, $this->endTime, SeparateTimeLogModel::TYPE_CLICKHOUSE);

            // clickhouse
            return self::CLICKHOUSE;
        }

        // 跨越了隔断日期
        throw new CommonException(CommonCodeEnum::ERR_SEPARATOR_TIME);
    }
}
